const Router = require('koa-router')
const { objectFiltering } = require('object-filtering')
const { RegisterValidator, LoginValidator } = require('@validator')
const { User } = require('@models/user')
const { Blog } = require('@models/blog')
const { Auth } = require('@root/middlewares/auth')
const { success } = require('@root/app/lib/helper')

const router = new Router({
  prefix: '/v1/user'
})

router.get('/blog', new Auth().m, async (ctx, next) => {
  const id = ctx.auth.uid
  const blog = await Blog.findAll({
    where: {
      user_id: id
    }
  })
  ctx.body = blog
})

/**
 * @description: 获取用户信息
 * @param {type} 
 * @return: 
 */
router.post('/', new Auth().m, async (ctx, next) => {
  const id = ctx.auth.uid
  const user = await User.findOne({
    where: {
      id
    }
  })
  if(!user) {
    throw new global.errors.NotFound('获取用户信息失败')
  }
  ctx.body = objectFiltering(user, {
    include: ['username', 'nickname']
  })
})

/**
 * @description: 注册
 * @param {type} 
 * @return: 
 */
router.post('/register', async (ctx, next) => {
  const obj = await new RegisterValidator().validate(ctx)
  const user = {
    username: obj.get('body.username'),
    password: obj.get('body.password2'),
    nickname: obj.get('body.nickname')
  }
  await User.create(user)
  success('注册成功')  // 执行成功的操作很多种，这里只是其中一种形式而已 
})

/**
 * @description: 登录
 * @param {type} 
 * @return: 
 */
// router.post('/login', async (ctx, next) => {
//   const obj = await new LoginValidator().validate(ctx)
//   await User.verfiyUserNamePassword(obj.get('body.username'), obj.get('body.password'))
//   success('登录成功')
// })

module.exports = router